//
//  SessionMySQLORM.swift
//  ECApp
//
//  Created by ping Cheng on 2017/10/26.
//

import Foundation

import MySQLStORM
import PerfectLogger
import PerfectHTTP

public class MySQLSessionsManage{
    public init() {}
    public func clean() {
        var session =  PerfectSessionORM()
        do {
            let stmt = "DELETE FROM \(session.table) WHERE updated + idle < ?"
            try session.select(whereclause: stmt, params: [Int(Date().timeIntervalSince1970)], orderby: [])
            print(session.rows)
            for row in session.rows(){
               try  row.delete()
            }
           
         
        } catch {
            LogFile.error("插入新session出错了")
        }
    }
    public func save(session: PerfectSessionORM) {
        do {
            try session.save()
            
        } catch {
            LogFile.error("更新session出错了")
        }
        
    }
    public func start(_ request: HTTPRequest,userId:Int) -> PerfectSessionORM {
        var session =  PerfectSessionORM()
        
        session.token = UUID().uuidString
        session.ipaddress = request.remoteAddress.host
        session.useragent = request.header(.userAgent) ?? "unknown"
        session._state = "new"
        session.setCSRF()
        
        do {
            try session.create()
        } catch {
            LogFile.error("插入新session出错了")
        }
        return session
    }
    /// Deletes the session for a session identifier.
    public func destroy(token:String) {
        var session =  PerfectSessionORM()
        do {
            try session.delete(token)
        } catch {
            LogFile.error("删除session失败，sessionid = \(token)")
        }
    }
    
    public func resume(token: String) -> PerfectSessionORM {
         var session =  PerfectSessionORM()
        do {
            try session.get(token)
        } catch {
            LogFile.error("获取session失败，sessionid = \(token)")
        }
        
         return session
    }
    
}



